package com.showcai.controller.pay;

import com.showcai.controller.base.WeChatBaseController;
import com.showcai.controller.utils.WeChatTools;
import com.showcai.def.Constant;
import com.showcai.module.*;
import com.showcai.myRunTime.MyRunTimeExcption;
import com.showcai.redis.RedisCache;
import com.showcai.result.ResultObj;
import com.showcai.result.ReturnCode;
import com.showcai.service.ApplyService;
import com.showcai.service.OrderItemService;
import com.showcai.service.OrderService;
import com.showcai.service.PayService;
import com.showcai.tools.HttpClientHelper;
import com.showcai.tools.sms.SMSTools;
import com.showcai.util.FixedData;
import com.showcai.util.GenerateID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Baggio on 2018-1-25.
 */
@RequestMapping("/pay")
@Controller
public class PayController extends WeChatBaseController {
    @Autowired
    private PayService weChatPayService;
    @Autowired
    OrderService orderService;
    @Autowired
    OrderItemService orderItemService;
    @Autowired
    ApplyService applyWatchService;
    @Autowired
    RedisCache redisCache;
    @RequestMapping(value = "/toPay")
    @ResponseBody
    public String toPay(Long orderId, String paymentJSON) {
        ResultObj resultObj = new ResultObj();
        PayParameter payParameter = null;
        try {

            User user=(User)session.getAttribute(Constant.SESSION_KEY_USER_LOGIN);
            if(user==null){
//                throw new MyRunTimeExcption("用户没有登录！");
            }
            String remoteAddr = request.getRemoteAddr();
            System.out.println("remoteAddr===>" + remoteAddr);
            String openid = (String) request.getSession().getAttribute(Constant.SESSION_OPEN_ID);
            logger.info("session is==============>>>"+session.getId());
            logger.info("openId===>" + openid);
           Byte payMode = orderService.toPay(orderId,  paymentJSON);
              logger.info("payMOde is==>>>"+payMode);
            Map<String, String> payParametersMap = new HashMap<>();
           Order order=orderService.getOrderById(orderId);
            payParametersMap.put("openid", openid);
           String  payParameterStr= orderService.payParameterStrBypayMode(payMode,orderId, order.getOrderPrice(), remoteAddr, payParametersMap);
           //payService.getPayParameterStr(String.valueOf(orderId), String.valueOf(order.getOrderPrice()), remoteAddr, payParametersMap);

            String dataString = HttpClientHelper.stringPost(FixedData.CREATE_ORDER_URL, payParameterStr);
            logger.info("【下单xml请求字符串：" + payParameterStr + "】。。。。。。");
              payParameter=   orderService.getPayParameterBypayMode(payMode,orderId,order.getOrderPrice(),dataString,WeChatTools.getTicket());
            resultObj.setData(payParameter);
            logger.info("payParameter===>" + payParameter.toString());
        } catch (MyRunTimeExcption runTimeExcption) {
            logger.info(runTimeExcption.getMessage());
            resultObj.setCode(ReturnCode.FAIL.getCode());
            resultObj.setMsg(runTimeExcption.getMessage());
            runTimeExcption.printStackTrace();
        } catch (Exception e) {
            logger.info(e.getMessage());
            e.printStackTrace();
            resultObj.setCode(ReturnCode.FAIL.getCode());
            resultObj.setMsg(e.getMessage());

        }
        //   return "redirect:" + bankUrl;
        //return new RedirectView(payParameter.getBankUrl(),true,false,false);//最后的参数为false代表以post方式提交请求
        //return new ModelAndView(new RedirectView(payParameter.getBankUrl()), payParameter.getMap());
        return resultObj.toJson();
    }
    /**
     * 客户支付后微信的回调接口
     * @param request
     * @return
     */
    @RequestMapping(value = "/notification")
    @ResponseBody
    public String notification(HttpServletRequest request) {

        InputStream inputStream = null;
        BufferedReader bufferedReader = null;

        try {
            inputStream = request.getInputStream();
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));

            String str;
            StringBuilder xmlString = new StringBuilder();
            while ((str = bufferedReader.readLine()) != null) {
                xmlString.append(str);
            }
            try {
                bufferedReader.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            Map<String, String> xml = new HashMap<String, String>();
            xml.put("xml", xmlString.toString());
            Map<String, String> returnMap = weChatPayService.notification(xml);
            return returnMap.get("xml");
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }


    @RequestMapping(value = "/pay/{orderId}")
    public ModelAndView pay(HttpServletRequest request,@PathVariable("orderId") Long orderId) {        // source: 1(来源于网站) | 2(来源于微站)
        ModelAndView mov = new ModelAndView();
        mov.setViewName("/pay/web/pay");
        System.out.println(orderId);
        if(super.getIsMobile()){
          //  super.oauth2();
            mov.setViewName("/pay/wap/pay");
        }
       Order order=orderService.getOrderById(orderId);
       List<OrderItem> orderItemList=orderItemService.getOrderItemByOrderId(orderId);
       ApplyWatch applyWatch=(ApplyWatch) applyWatchService.selectApplyByOrderId(orderId);
        mov.addObject("order",order);
        mov.addObject("orderItemList",orderItemList);
        mov.addObject("applyWatch",applyWatch);
        return mov;
    }

    /**
     * 支付结果
     * @param orderId
     * @return
     */
    @RequestMapping(value = "/payResult")
    public ModelAndView payResult( Long orderId) {
        ModelAndView mov = new ModelAndView();
        mov.setViewName("/pay/web/payResult");

        if(super.getIsMobile()){
            String UUID =  GenerateID.getUUID();
            logger.info("userTokenCode is===>"+UUID);
            logger.info("orderId is===>"+orderId);
              List<Long> activityList=null;

            try {
                redisCache.put(UUID,orderId,120);
                mov.addObject("userTokenCode",UUID);
                Order order=orderService.getOrderById(orderId);
                activityList=order.getActivityIdList();
                Long userId=order.getUserId();
                User user=userService.getUserById(userId);
                SMSTools.sendSMS("",user.getPhone(),SMSTools.SMS_NOTIFIY);
            } catch (Exception e) {
                e.printStackTrace();
            }
     mov.addObject("activityList",activityList);
     mov.setViewName("/pay/wap/payResult");

        }
/*        Order order=orderService.getOrderById(orderId);
        mov.addObject("order",order);*/
        return mov;
    }
 /**
     * 支付结果
     * @param orderId
     * @return
     */
    @RequestMapping(value = "/paySucc")
    public ModelAndView paySucc(Long orderId) {
        ModelAndView mov = new ModelAndView();
        mov.setViewName("/pay/web/paySucc");

        if(super.getIsMobile()){

            mov.setViewName("/pay/wap/paySucc");
        }
/*        Order order=orderService.getOrderById(orderId);
        mov.addObject("order",order);*/
        return mov;
    }



}
